package com.kingtroldata.autosort_demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bt1, bt2, bt3, bt4;
    private AutoSort autoSort;
    private LinearLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        //必须调用,初始化操作
        autoSort = AutoSort.init();
    }

    private void initListener() {
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        bt3.setOnClickListener(this);
        bt4.setOnClickListener(this);
    }

    private void initView() {
        bt1 = (Button) findViewById(R.id.bt1);
        bt2 = (Button) findViewById(R.id.bt2);
        bt3 = (Button) findViewById(R.id.bt3);
        bt4 = (Button) findViewById(R.id.bt4);
        container = (LinearLayout) findViewById(R.id.ll_container);
    }

    @Override
    public void onClick(View v) {
        String key = String.valueOf(v.getId());
        //当点击的时候调用,将唯一标识传递进去
        autoSort.add(key);
        showView();
        showMap();
        showData(8);
    }

    private void showView() {
        String[] values = autoSort.getValues(3);
        container.removeAllViews();
        for (String val : values) {
            TextView tv = new TextView(this);
            tv.setText(val);
            container.addView(tv);
        }
    }

    private void showData(int count) {
        String[] values = autoSort.getValues(count);
        for (String val : values) {
            LoggerUtils.e(val);
        }
    }

    private void showMap() {
        TreeMap<Integer, String> map = autoSort.getMap();
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        LoggerUtils.e("============================");
        for (Map.Entry<Integer, String> entry : entries) {
            Integer k = entry.getKey();
            String val = entry.getValue();
            LoggerUtils.e("key:" + k + ";value:" + val);
        }
        LoggerUtils.e("============================");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //必须调用,保存数据
        autoSort.savaData();
    }
}
